package com.mgg.goods.service.stock.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.mgg.common.dao.DaoSupport;
import com.mgg.goods.service.stock.StockService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component("stockService")
public class StockServiceImpl implements StockService{

	@Autowired
	private DaoSupport dao;
	
	/**
	 * 修改订单商品库存数量
	 */
	@Transactional
	@Override
	public void changeGoodsInvByOrder(List<Map<String,Object>> skuList, String operate, String orderId) {
		
		for (Map<String,Object> sku : skuList) {
			String specId = sku.get("spec_id").toString();
			Integer num = Integer.parseInt(sku.get("num").toString());
			updateGoodsSpecQty(specId,num,operate,orderId);		
			
			//修改组合商品库存
			List<Map<String,Object>> list = dao.findForList("StockMapper.listCombinationGoodsNum", specId);
			for (Map<String,Object> combSku : list) {
				specId = combSku.get("spec_id").toString();
				num = Integer.parseInt(combSku.get("num").toString());
				updateGoodsSpecQty(specId,num,operate,orderId);	
			}
		}
	}

	private void updateGoodsSpecQty(String specId, Integer num, String operate, String orderId) {
		Map<String,Object> map = new HashMap<>();
		map.put("spec_id", specId);
		Integer sellQty = (Integer) dao.findForObject("StockMapper.getGoodsSpecSellQty", specId);
		if("reduce".equals(operate)) {
			if (sellQty >= num) {
				map.put("sell_qty", -num);	
				map.put("virtual_qty", 0);	
			} else {
				map.put("sell_qty", -sellQty);	
				map.put("virtual_qty", -(num - sellQty));	
			}	
			map.put("inv_qty", -num);
			map.put("sales_qty", num);
			map.put("remark", "提交订单减库存");
			dao.update("StockMapper.updateGoodsSpecQty", map);	
		} else if("add".equals(operate)) {
			map.put("sell_qty", num);	
			map.put("virtual_qty", 0);	
			map.put("inv_qty", num);
			map.put("sales_qty", -num);
			map.put("remark", "取消订单恢复库存");
			dao.update("StockMapper.updateGoodsSpecQty", map);	
		}
		map.put("order_id", orderId);
		dao.save("StockMapper.insertGoodsSpecQtyLog", map);
	}
}
